package com.qf.SpringSecurity;

import com.qf.entity.SysUser;
import com.qf.mapper.SysPermissionMapper;
import com.qf.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName: MyUserDetailsService
 * @Author: WangHao
 * @Date: 2025/5/7 10:21
 * @Description:
 * @Version: 1.0
 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser sysUser = sysUserMapper.loginByUsername(username);
        if(sysUser == null){
            // 这个异常是SpringSecurity提供的
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        Set<String> permissions = sysPermissionMapper.selectByUserId(sysUser.getId());
        System.out.println("------------permissions---------------- = " + permissions);
        Set<GrantedAuthority> auths = new HashSet<>();
        // 遍历权限，将权限添加到权限集合中
        permissions.forEach(item -> auths.add(new SimpleGrantedAuthority(item)));
        // 此处的User是SpringSecurity提供的，User对象包含了用户名、密码、权限等信息
        // import org.springframework.security.core.userdetails.User;
        return new User(sysUser.getUsername(), sysUser.getPassword(),auths);
    }
}
